/*
 * Main.c
 *
 *  Created on: 16 juli 2021
 *      Author: Daniel Mårtensson
 */

#include <stdio.h>

 /* Include Open SAE J1939 */
#include "Open_SAE_J1939/Open_SAE_J1939.h"

int main() {

	/* Create our J1939 structure with two ECU */
	J1939 j1939_1 = { 0 };
	J1939 j1939_2 = { 0 };

	/* Important to sent all non-address to 0xFF - Else we cannot use ECU address 0x0 */
	uint8_t i;
	for (i = 0; i < 255; i++) {
		j1939_1.other_ECU_address[i] = 0xFF;
		j1939_2.other_ECU_address[i] = 0xFF;
	}

	/* Set the ECU address */
	j1939_1.information_this_ECU.this_ECU_address = 0x80;												/* From 0 to 253 because 254 = error address and 255 = broadcast address */
	j1939_2.information_this_ECU.this_ECU_address = 0x90;

	/* This is important because length_of_each_field is not a SAE J1939 standard. The software need to know how large field it is from the beginning */
	j1939_2.from_other_ecu_identifications.ecu_identification.length_of_each_field = 30;

	/* Set the ECU Identification */
	j1939_1.information_this_ECU.this_identifications.ecu_identification.length_of_each_field = 30;
	char ecu_part_number[20] = "ABC-1100P-XXXX10";
	char ecu_serial_number[20] = "1-200-K-10M";
	char ecu_location[20] = "Under bridge";
	char ecu_type[20] = "Model G";
	for (i = 0; i < 20; i++) {
		j1939_1.information_this_ECU.this_identifications.ecu_identification.ecu_part_number[i] = (uint8_t)ecu_part_number[i];
		j1939_1.information_this_ECU.this_identifications.ecu_identification.ecu_serial_number[i] = (uint8_t)ecu_serial_number[i];
		j1939_1.information_this_ECU.this_identifications.ecu_identification.ecu_location[i] = (uint8_t)ecu_location[i];
		j1939_1.information_this_ECU.this_identifications.ecu_identification.ecu_type[i] = (uint8_t)ecu_type[i];
	}

	/* Request Software Identification from ECU 2 to ECU 1 */
	SAE_J1939_Send_Request(&j1939_2, 0x80, PGN_ECU_IDENTIFICATION);

	/* Response request from ECU 1 perspective - Don't worry, in real CAN applications you don't need this mess. */
	Open_SAE_J1939_Listen_For_Messages(&j1939_1);
	Open_SAE_J1939_Listen_For_Messages(&j1939_2);
	Open_SAE_J1939_Listen_For_Messages(&j1939_1);

	/* Read response request from ECU 1 to ECU 2 */
	for (i = 0; i < 15; i++) {
		Open_SAE_J1939_Listen_For_Messages(&j1939_2);
		Open_SAE_J1939_Listen_For_Messages(&j1939_1);
	}

	/* Display what ECU 2 got */
	printf("Length of each field = %i\nECU part number = %s\nECU serial number = %s\nECU location = %s\nECU type = %s\nFrom ECU address 0x%X"
		, j1939_2.from_other_ecu_identifications.ecu_identification.length_of_each_field
		, j1939_2.from_other_ecu_identifications.ecu_identification.ecu_part_number
		, j1939_2.from_other_ecu_identifications.ecu_identification.ecu_serial_number
		, j1939_2.from_other_ecu_identifications.ecu_identification.ecu_location
		, j1939_2.from_other_ecu_identifications.ecu_identification.ecu_type
		, j1939_2.from_other_ecu_identifications.ecu_identification.from_ecu_address);

	return 0;
}
